package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.common.utils.DateUtil;
import com.common.utils.MeUtils;
import com.common.utils.Result;
import com.common.utils.StringUtil;
import com.entity.Card;
import com.entity.Node;
import com.mapper.CardMapper;
import com.query.CardQuery;
import com.service.CardService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.NodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wty
 * @since 2022-01-04
 */
@Service
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements CardService {

    @Autowired
    private NodeService nodeService;

    @Override
    @Transactional
    public Result addCard(Card card) {

        try{
            Integer id = card.getId();
            if(null==id){
                this.insert(card);
                Result.success("添加成功");
            }

            this.insert(card);
            Node node = nodeService.selectById(id);
            if(null==node){
                return  Result.error("添加失败");
            }

            String cardId = node.getCardId();
            if(!StringUtil.isEmpty(cardId)){
                List<String> cardIds = JSONArray.parseArray(cardId, String.class);
                cardIds.add(card.getId().toString());
                node.setCardId(JSON.toJSONString(cardIds));
                nodeService.updateById(node);
            }else{
                List<String> cardIds =new ArrayList<>();
                cardIds.add(card.getId().toString());
                node.setCardId(JSON.toJSONString(cardIds));
                nodeService.updateById(node);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  Result.error("添加失败");
        }

        return  Result.success("添加成功");
    }

    @Override
    public Result uploadImg(MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "Hps7KCWqWEKSeTNO";
        String accessKeySecret = "F0ADiw4Rne216mThd6Epey6nG9D8XQ";
// 填写Bucket名称，例如examplebucket。
        String bucketName = "andi159753";
// 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。

        //提醒插入数据库
        String objectName = "img/" + "yi" + "_" + DateUtil.getLongByCurrTime() + ".jpg";
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//            String imgr = "http://webquotepic.eastmoney.com/GetPic.aspx?nid=" + imgcode + "&imageType=r";
//            String img = MeUtils.imgBase64(imgr);
//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] file1 = new byte[0];
//            try {
//                file1 = decoder.decodeBuffer(img);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(file.getBytes().length);
            InputStream input = new ByteArrayInputStream(file.getBytes());
            ossClient.putObject(bucketName, objectName, input, objectMeta);
            return Result.success(objectName);
        }catch (Exception e){

        }

        return null;
    }

    /**
     * 根据条件查询卡牌
     * @param cardQuery
     * @return
     */
    @Override
    public Result getCardList(CardQuery cardQuery) {
        Integer nodeId = cardQuery.getNodeId();
        String content = cardQuery.getContent();

        Wrapper<Card> wr=new EntityWrapper<>();

        if(null!=nodeId){
            Node node = nodeService.selectById(nodeId);
            String cardId = node.getCardId();
            if(!StringUtils.isEmpty(cardId)){
                List<String> strings = JSONArray.parseArray(cardId, String.class);
                wr.in("id",strings);
            }
        }
        if(!StringUtils.isEmpty(content)){
            wr.like("content",content);
        }

        List<Card> cardList = this.selectList(wr);
        return Result.success(cardList);
    }
}
